package com.yztc.xiami_app.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yztc.xiami_app.R;
import com.yztc.xiami_app.helper.baidumap.ILocationListener;
import com.yztc.xiami_app.helper.baidumap.MapLocation;
import com.yztc.xiami_app.ui.customletterindexview.ChineseToPinyinHelper;
import com.yztc.xiami_app.ui.customletterindexview.LetterIndexerView;
import com.yztc.xiami_app.ui.customletterindexview.MySortAdapter;
import com.yztc.xiami_app.ui.customletterindexview.UserModel;
import com.yztc.xiami_app.ui.receiveaddress.interfaces.IAddressSelectListener;
import com.yztc.xiami_app.ui.receiveaddress.presenter.IReceiveAddressPresenter;
import com.yztc.xiami_app.ui.receiveaddress.presenter.ReceiveAddressPresenterImpl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * “收货地址”的首界面
 */
public class ReceiveAddressActivity extends AppCompatActivity implements IAddressSelectListener {


    @BindView(R.id.back_home_page_iv)
    ImageView backHomePageIv; //返回主界面的按钮
    @BindView(R.id.receive_address_tv)
    TextView receiveAddressTv; //ToolBar的收货地址
    @BindView(R.id.location_result_tv)
    TextView locationResultTv; //定位的结果


    //    -----------收货地址字母索引Start---------------------
    private ListView listView_main;
    private TextView textView_empty;
    private TextView textView_dialog;
    private LetterIndexerView letterIndexerView_main;
    private List<UserModel> totalList = new ArrayList<UserModel>();
    private MySortAdapter adapter = null;

//        -----------收货地址字母索引End---------------------

    private Context mContext;
    private List<String> mCityList = new ArrayList<>(); //收货的城市列表的数据源
    private IReceiveAddressPresenter mReceiveAddressPresenter;
    private ILocationListener locationListener = new ILocationListener() {
        @Override
        public void getAddress(String address) {
            locationResultTv.setText(address); //设置定位的精确结果
        }

        @Override
        public void getCity(String city) {
            receiveAddressTv.setText("收货地址-"+city);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_address);
        ButterKnife.bind(this);

        mContext = this;
        initView();
        getLocationResult();
        initPresenter();


    }

    private void initPresenter() {
        mReceiveAddressPresenter = new ReceiveAddressPresenterImpl();
    }


    //获取百度定位的结果
    private void getLocationResult() {
        MapLocation location = new MapLocation(this, locationListener);
        location.getAddress(); //获取定位地址，需要接口回调来接收
    }


    //字母索引布局的初始化
    private void initView() {
        listView_main = (ListView) findViewById(R.id.listView_main);
        textView_empty = (TextView) findViewById(R.id.textView_empty);
        textView_dialog = (TextView) findViewById(R.id.textView_dialog);
        letterIndexerView_main = (LetterIndexerView) findViewById(R.id.letterIndexerView_main);
        letterIndexerView_main.initTextView(textView_dialog);

        totalList = getUserList();
        // 要对集合重新进行排序
        Collections.sort(totalList, new Comparator<UserModel>() {
            @Override
            public int compare(UserModel lhs, UserModel rhs) {
                if (lhs.getFirstLetter().equals("#")) {
                    return 1;
                } else if (rhs.getFirstLetter().equals("#")) {
                    return -1;
                } else {
                    return lhs.getFirstLetter().compareTo(rhs.getFirstLetter());
                }
            }
        });

        adapter = new MySortAdapter(this, totalList, this);
        listView_main.setAdapter(adapter);
        listView_main.setEmptyView(textView_empty);

        letterIndexerView_main
                .setOnLetterClickedListener(new LetterIndexerView.OnLetterClickedListener() {
                    @Override
                    public void onLetterClicked(String letter) {
                        int position = adapter.getPositionForSection(letter
                                .charAt(0));
                        listView_main.setSelection(position);
                    }
                });

    }

    //字母索引对应的省份列表的布局的数据源
    private List<UserModel> getUserList() {
        List<UserModel> list = new ArrayList<UserModel>();
        String[] arrUserNames = getResources().getStringArray(
                R.array.arrProvinces);
        for (int i = 0; i < arrUserNames.length; i++) {
            UserModel userModel = new UserModel();
            String username = arrUserNames[i];
            String pinyin = ChineseToPinyinHelper.getInstance().getPinyin(
                    username);
            String firstLetter = pinyin.substring(0, 1).toUpperCase();

            userModel.setUsername(username);
            userModel.setPinyin(pinyin);

            if (firstLetter.matches("[A-Z]")) {
                userModel.setFirstLetter(firstLetter);
            } else {
                userModel.setFirstLetter("#");
            }
            list.add(userModel);
        }
        return list;
    }

    //省份列表的Item的点击事件的处理
    @Override
    public void provinceItemClick(String provinceName) {

        final String[] arrCities = mReceiveAddressPresenter.getCityData(mContext, provinceName);

        //弹出列表对话框，用于显示选择的省份对应的城市的列表
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.receive_address_area) //设置标题
                .setItems(arrCities, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //弹出列表对话框，用于显示选择的城市对应的区/县的列表
                        showAreaDialog(arrCities[which]);
                    }
                })
                .create().show();
    }

    //用于显示选择的城市对应的区/县的列表
    private void showAreaDialog(String cName){
        //获取指定市下的所有区
        String[] arrAreas = mReceiveAddressPresenter.getAreaData(mContext, cName);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.receive_address_area) //设置标题
                .setItems(arrAreas, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //弹出列表对话框，用于显示选择的城市对应的区/县的列表
                    }
                })
                .create().show();
    }

    //返回首页
    @OnClick(R.id.back_home_page_iv)
    public void onClick() {
        //返回首页
        Intent intent = new Intent(mContext, MainActivity.class);
        startActivity(intent);
    }
}
